<template>
  <!-- 头部导航栏 -->
  <view class="navbar" :style="{ paddingTop: menu.top + 'px' }">
    <image src="http://xcxtp.njmswl.com/images/goBack.png" class="goBack" @tap="goBack" />
    <text class="title">新房源</text>
  </view>

  <view class="search">
    <image  @click="searchBtn"   src="http://xcxtp.njmswl.com/images/search.png" class="searchImg" />
    <input  v-model="pageParams.name" @change="searchBtn"  type="text" class="input" placeholder="请输入小区/商圈" />
  </view>
  <view class="screen">
    <view class="screenItem" @tap="selectItemType('二手房')">
      <text class="screen-text">二手房</text>
      <text class="line" :class="{ active: selectedType === '二手房' }"></text>
    </view>
    <view class="screenItem" @tap="selectItemType('新房')">
      <text class="screen-text">新房</text>
      <text class="line" :class="{ active: selectedType === '新房' }"></text>
    </view>
    <view class="screenItem">
      <text class="screen-text" @tap="selectItemType('租房')">租房</text>
      <text class="line" :class="{ active: selectedType === '租房' }"></text>
    </view>
  </view>
  <scroll-view
    class="scroll-view"
    @scrolltolower="onScrolltolower"
    @refresherrefresh="OnRefresherRefresh"
    refresher-enabled="true"
    :refresher-triggered="isTriggered"
    scroll-y
  >
    <view
      v-if="!isAccessTokenSet"
      class="content"
      v-for="item in list"
      :key="item.id"
      @click="detail(item.id)"
    >
      <button
        open-type="getPhoneNumber"
        @getphonenumber="onGetphonenumber"
        style="height: 230rpx"
      >
        <view class="contentItem">
          <image :src="item.images && item.images.length ? item.images[0] : defaultImage" class="contentItemImg" />
          <view class="description">
            <p class="desTitle">{{ item.name }}</p>
            <p class="positionContent">
              <span class="houseTag">{{ item.area }}</span>
              <span class="houseTag">{{ item.asaga }}</span>
              <span class="houseTag">{{ item.communityAddress }}</span>
              <span class="houseTag">{{ item.geoLoc }}</span>
            </p>
            <p class="priceContent">
              <span class="allPrice">{{ item.price + "元/月" }}</span>
            </p>
            <p class="tagContent">
         <span class="houseLabel" v-for="(item, index) in item.tags" :key="index">{{
                    item
                  }}</span>
            </p>
          </view>
        </view>
      </button>
    </view>
    <view
      v-else
      class="content"
      v-for="item in list"
      :key="item.id"
      @click="goDetail(item.id)"
    >
      <view class="contentItem">
        <image :src="item.images && item.images.length ? item.images[0] : defaultImage" class="contentItemImg" />
        <view>
          <p class="desTitle">{{ item.name }}</p>
          <p>
            <span class="houseTag">{{ item.area }}</span>
            <span class="houseTag">{{ item.asaga }}</span>
            <span class="houseTag">{{ item.communityAddress }}</span>
            <span class="houseTag">{{ item.geoLoc }}</span>
          </p>
          <p>
            <span class="allPrice">{{ item.price + "元/月" }}</span>
          </p>
          <p>
              <span class="houseLabel" v-for="(item, index) in item.tags" :key="index">{{
                    item
                  }}</span>
          </p>
        </view>
      </view>
    </view>
    <open-program></open-program>
  </scroll-view>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { onLoad, onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
import { getSecondHandPageAPI } from "@/services/secondHand";
import { getLoginAPI, getSocialLoginAPI } from "@/services/login";
import openProgram from "../components/openProgram.vue";
import { getNewHousePageAPI } from "@/services/newHouse";
import { getRentHousePageAPI } from "@/services/rentHouse";
const menu = ref({});
const label = ref(["近地铁", "新上", "精装修"]);
const tag = ref(["86.02㎡", "南", "浦口", "桥北"]);
const list = ref([]);
// 二手房数据请求
//1.分页参数
const pageParams = {
  pageNo: 1,
  pageSize: 5,
  name:''
};
//2. 分页已结束标记
const finish = ref(false);
//二手房分页数据请求
const getSecondHandPage = async () => {
  // 数据加载完，退出继续追加分页数据
  if (finish.value === true) {
    return uni.showToast({
      icon: "none",
      title: "没有更多数据了~",
    });
  }
  const res = await getSecondHandPageAPI(pageParams);
  list.value.push(...res.data.list);
  if (pageParams.pageNo < res.data.total / pageParams.pageSize) {
    pageParams.pageNo++;
  } else {
    finish.value = true;
  }
};

// 二手房下拉刷新函数
const refreshSecondHandPage = async () => {
  const res = await getSecondHandPageAPI({
    pageNo: 1,
    pageSize: 5,
  });
  list.value = res.data.list;
  finish.value = false
};



onMounted(() => {
  menu.value = uni.getMenuButtonBoundingClientRect();
  console.log(menu.value);
});
const goBack = () => {
  uni.switchTab({
    url: "/pages/index/index", // 这里的url是你首页的路径，根据你的项目实际情况进行修改
  });
};
onLoad(() => {
  updateIsAccessTokenSet()
  getSecondHandPage();
});
//uniapp微信小程序分享页面到微信好友
onShareAppMessage(() => {});
//uniapp微信小程序分享页面到微信朋友圈

onShareTimeline(() => {});
const selectedType = ref("二手房");

// 搜索点击
const searchBtn = ()=>{
  fetchData(selectedType.value)
}

// 处理点击事件的方法，更新selectedType
const selectItemType = (type) => {
  selectedType.value = type;
  pageParams.name = ''
  fetchData(type); // 根据类型发起请求
};
const flag = ref(2);
// 滚动触底 加载更多
const onScrolltolower = () => {
  if (flag.value == 2) {
    getSecondHandPage();
  }
  if (flag.value == 1) {
    getNewHousePageList();
  }
  if (flag.value == 3) {
    getRentHousePageList();
  }
};
const fetchData = async (type) => {
  try {
    // 根据不同的类型发起不同的请求
    switch (type) {
      case "新房":
        const newHouseRes = await getNewHousePageAPI({
          pageNo: 1,
          pageSize: 5,
          name:pageParams.name
        });
        list.value = newHouseRes.data.list;
        flag.value = 1;
        break;
      case "二手房":
        const secondHouseRes = await getSecondHandPageAPI({
          pageNo: 1,
          pageSize: 5,
          name:pageParams.name
        });
        list.value = secondHouseRes.data.list;
        flag.value = 2;
        break;
      case "租房":
        const rentHouseRes = await getRentHousePageAPI({
          pageNo: 1,
          pageSize: 5,
          name:pageParams.name
        });
        list.value = rentHouseRes.data.list;
        flag.value = 3;
        break;
      default:
        console.log("未知类型");
    }
  } catch (error) {
    console.error("数据请求错误:", error);
  }
};
//进入详情页先获取id值
const detailId = ref(); //详情信息id
const detail = (id) => {
  detailId.value = id;
};
// ----------------------- 登录获取手机号方法 参数：1.code 2.encryptedData 3.iv
const isAccessTokenSet = ref(!!uni.getStorageSync("accessToken"));
const updateIsAccessTokenSet = () => {
  isAccessTokenSet.value = !!uni.getStorageSync('accessToken')
}
const time = ref()
//-------------------token过期---------------------------------------------------------------------------------
function myFunction() {
  time.value = uni.getStorageSync('expiresTime')||0
  // 获取当前系统时间的时间戳
  const currentTimeTimestamp = Date.now()
  // 检查Token是否过期
  if (time.value === 0) {
  } else if (currentTimeTimestamp >= time.value) {
    uni.showToast({
      title: '登录过期，请重新登录！',
      icon: 'none',
      duration: 2000,
      mask: true,
      success: function () {
        // 清理存储
        uni.removeStorageSync('accessToken')
        uni.removeStorageSync('appIdKey')
        uni.removeStorageSync('expiresTime')
      },
    })
  } else {
  }
}
const intervalId = setInterval(myFunction, 1000)
//-------------------------------------------------------------------------------------
const scene = ref()
const onGetphonenumber: UniHelper.ButtonOnGetphonenumber = async (ev) => {
  const encryptedData = ev.detail.encryptedData;
  const iv = ev.detail.iv;
  const isId = uni.getStorageSync("appIdKey");
    scene.value = uni.getStorageSync('scene')
  const res = await getSocialLoginAPI({
    code: ev.detail.code,
    encryptedData: encryptedData,    
    iv: iv,
    sourceUserId:scene.value
  })
  const bearer = "Bearer ";
  uni.setStorageSync("appIdKey", res.data.userId);
  uni.setStorageSync("accessToken", bearer + res.data.accessToken);
  uni.setStorageSync('expiresTime', res.data.expiresTime)
  updateIsAccessTokenSet()
  const detail = detailId.value;
  const flagValue = flag.value;
  if (flagValue == 2) {
    //二手房标志
    uni.navigateTo({
      url: `/pages/simplePage/secondHandDetail?id=${detail}`,
    });
  } else if (flagValue == 1) {
    //新房标志
    uni.navigateTo({
      url: `/pages/simplePage/newHouseDetail?id=${detail}`,
    });
  } else if (flagValue == 3) {
    //租房标志
    uni.navigateTo({
      url: `/pages/simplePage/rentHouseDetail?id=${detail}`,
    });
  }
};
const goDetail = (id) => {
  const flagValue = flag.value;
  if (flagValue == 2) {
    //二手房标志
    uni.navigateTo({
      url: `/pages/simplePage/secondHandDetail?id=${id}`,
    });
  } else if (flagValue == 1) {
    //新房标志
    uni.navigateTo({
      url: `/pages/simplePage/newHouseDetail?id=${id}`,
    });
  } else if (flagValue == 3) {
    //租房标志
    uni.navigateTo({
      url: `/pages/simplePage/rentHouseDetail?id=${id}`,
    });
  }
};

//下拉刷新-------------------------------------------------------------------------------------
const isTriggered = ref(false);
const OnRefresherRefresh = async () => {
  isTriggered.value = true;
  if (flag.value === 0) {
    await Promise.all([refreshSecondHandPage()]);
  }
  if (flag.value === 1) {
    await Promise.all([refreshNewHousePage()]);
  }
  if (flag.value === 2) {
    await Promise.all([refreshSecondHandPage()]);
  }
  if (flag.value === 3) {
    await Promise.all([refreshRentHousePage()]);
  }

  isTriggered.value = false;
};
//新房分页数据请求
const getNewHousePageList = async () => {
  // 数据加载完，退出继续追加分页数据
  if (finish.value === true) {
    return uni.showToast({
      icon: "none",
      title: "没有更多数据了~",
    });
  }

  const res = await getNewHousePageAPI(pageParams);
  list.value.push(...res.data.list);
  if (pageParams.pageNo < res.data.total / pageParams.pageSize) {
    pageParams.pageNo++;
  } else {
    finish.value = true;
  }
};


// 新房下拉刷新函数
const refreshNewHousePage = async () => {
  const res = await getNewHousePageAPI({
    pageNo: 1,
    pageSize: 5,
  });
  list.value = res.data.list;
  finish.value = false
};

// 获取租房分页数据列表
const getRentHousePageList = async () => {
  // 数据加载完，退出继续追加分页数据
  if (finish.value === true) {
    return uni.showToast({
      icon: "none",
      title: "没有更多数据了~",
    });
  }
  const res = await getRentHousePageAPI(pageParams);
  if (res.code == 0) {
    list.value.push(...res.data.list);
  }

  list.value.push(...res.data.list);
  // console.log(list.value);
  if (pageParams.pageNo < res.data.total / pageParams.pageSize) {
    pageParams.pageNo++;
  } else {
    finish.value = true;
  }
};
// 租房下拉刷新函数
const refreshRentHousePage = async () => {
  const res = await getRentHousePageAPI({
    pageNo: 1,
    pageSize: 5,
  });
  list.value = res.data.list;

  finish.value = false
};
//---------------------------------------------------------------
</script>
<style lang="scss">
.tagContent {
  height: 20rpx;
  left: 0;
  top: 100rpx;
  position: absolute;
}
.priceContent {
  height: 20rpx;
  left: 0;
  top: 60rpx;
  position: absolute;
}

.positionContent {
  height: 20rpx;
  left: 0;
  top: 50rpx;
  position: absolute;
  font-size: 20rpx;
}
.description {
  height: 200rpx;
  position: relative;
}
page {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
  background-color:  #f3f5fa;
}
.navbar {
  padding-left: 28rpx;
  padding-right: 37rpx;
  margin-top: 8rpx;
  background-color: #fff;
  background-size: cover;
  display: flex;
  align-items: center;
  .goBack {
    width: 18rpx;
    height: 30rpx;
    margin-top: 7rpx;
    margin-left: 28rpx;
  }

  .title {
    margin: 0 auto;
    font-family: PingFang SC;
    font-weight: 600;
    font-size: 36rpx;
    color: #000000;
  }
}

.search {
  display: flex;
  align-items: center;
  width: 695rpx;
  height: 70rpx;
  background: #f3f5fa;
  border-radius: 35rpx;
  margin-top: 37rpx;
  margin-left: 27rpx;

  .searchImg {
    width: 28rpx;
    height: 28rpx;
    margin-left: 25rpx;
    margin-right: 8rpx;
  }

  .input {
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 26rpx;
  }
}

.screen {
  position: relative;
  display: flex;
  width: 100%;
  padding-top: 43rpx;
  padding-bottom: 34rpx;
}

.screenItem {
  width: 33%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.screen-text {
  font-family: PingFang SC;
  font-weight: 550;
  font-size: 26rpx;
  color: #000000;
}

.line {
  position: absolute;
  bottom: 0;
  width: 27rpx;
  height: 0rpx;
  background: #16c686;
  border-radius: 2rpx;
}
.line.active {
  /* 选中时的下划线样式，例如实线、颜色改变等 */
  //   border-bottom: 1px solid #000; /* 示例：实线，黑色 */
  height: 4rpx;
}
.market {
  width: 10rpx;
  height: 6rpx;
  margin-left: 6rpx;
}

.content {
  display: flex;
  width: 750rpx;
  height: auto;
  background-color: #f4f5fc;
}

.contentItem {
  flex: 1;
  display: flex;
  align-items: center;
  width: 695rpx;
  height: 230rpx;
  background: #ffffff;
  border-radius: 20rpx;
  margin-left: 27rpx;
  margin-right: 27rpx;
  margin-top: 24rpx;

  .houseLabel {
    width: auto;
    height: 31rpx;
    background: #f3f4fa;
    border-radius: 3rpx;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 20rpx;
    color: #687a8c;
    padding: 6rpx 11rpx;
    margin-right: 9rpx;
  }

  .contentItemImg {
    width: 210rpx;
    height: 155rpx;
    background: #000000;
    border-radius: 5rpx;
    margin-left: 26rpx;
    margin-right: 21rpx;
  }
}

.desTitle {
  width: 410rpx;
  font-family: PingFang SC;
  font-weight: 550;
  font-size: 30rpx;
  color: #000000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: left;
}

.allPrice {
  font-family: PingFang SC;
  font-weight: 600;
  font-size: 30rpx;
  color: #e75841;
  margin-right: 14rpx;
}

.avgPrice {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 22rpx;
  color: #989b9e;
}

.houseTag {
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 20rpx;
  color: #020609;
  margin-right: 20rpx;
}
</style>
